$(function(){
	//常用UI组件封装
	var sys = {
		/**
		 * 日期/时间范围
		 * @author solin
		 * @date 
		 * @param config.id: 组件ID
		 * @param config.ctlObj 组件对象（通过$('#id')、$('.classsName')、$('input[name="name"]')等获取的组件对象）,如果
		 *		  				传入了id，则不需要再设置此参数。如果没有设置ID，则一定要设置此参数。
		 * @param config.type 'date'：日期，显示年月日; 'datetime':日期时间，显示年月日时分秒
		 * @param config.startDate 设置默认时间(date/string)
		 * @param config.maxDate 设置限制最大时间(date/string)
		 * @param callback 回调函数 function(start, end, label) { 
		 * 			console.log(start.format('YYYY-MM-DD'))
		 *			console.log(end.format('YYYY-MM-DD'))  
		 *		}
		 */
		daterangepicker: function(config, callback){
			if (typeof config == 'object') {
				if (!config['id'] && !config['ctlObj'] || !config['type']) {
					return false;
				}
				var $date = config.id ? $('#'+config.id) : config.ctlObj;
				var defaults = {
					startDate: moment().subtract(30, "days"), 
//					maxDate:new Date(),
					applyClass: "btn-primary",
					locale:{
						format: 'YYYY-MM-DD',
						daysOfWeek:["日","一","二","三","四","五","六"],
						monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
						applyLabel: "确定",
		        		cancelLabel: "取消",
					},
				};
				if (config.type=="datetime") { 
					defaults.locale.format = 'YYYY-MM-DD HH:mm:ss';
					defaults.timePicker = true;
					defaults.timePicker24Hour = true;
					defaults.timePickerSeconds = true;
				}
				
				config = $.extend(defaults, config || {});
				$date.daterangepicker(config, callback);
			}
		}
	}
	sys.daterangepicker({id: 'orderDate', type:'date',
		maxDate:new Date()
	});
	$('#orderDate').on('apply.daterangepicker', function(){
		queryOrderData();
	})
	$(".page_selector").sSelect();
	
	$('.dd_nav p a').click(function(){
		$(this).toggleClass('current');
		$(this).siblings().removeClass('current');
	});
//	queryOrderData();
	timeTypeChange();
	
	// 导出订单
	$("#btn_export_order_data").click(function(){
		//获取参数
//		var orderStatus = $("#orderStatus").val();
//		var orderStatusName = $("#orderStatusName").val();
//		var timeType = $("#timeType").val();
		var orderStatus = "02";
		var orderStatusName = "已付款";
		var timeType = "part";
		var searchDate = $("#orderDate").val();
		var startTime = null;
		var endTime = null;
		if (searchDate && searchDate.indexOf(' - ') > 0) {
			startTime = searchDate.split(' - ')[0];
			endTime = searchDate.split(' - ')[1];
		} 
		
		var form = getForm("/order/exportOrderData");
		form.append("<input type='hidden'  name='orderStatus'  value='"+orderStatus+"'/>");
		form.append("<input type='hidden'  name='orderStatusName'  value='"+orderStatusName+"'/>");
		form.append("<input type='hidden'  name='timeType'  value='"+timeType+"'/>");
		form.append("<input type='hidden'  name='startTime'  value='"+startTime+"'/>");
		form.append("<input type='hidden'  name='endTime'  value='"+endTime+"'/>");
		$(document.body).append(form);
		form.submit();
	});
});

//固定时长选择
function timeTypeChange(){
	var timeType = $("#timeTypeSel").find("option:selected").val();
	$("#timeType").val("part");
	var endDate = moment().format('YYYY-MM-DD');
	var beginDate = "";
	if (timeType == 'recent_fifteen_day') {
		beginDate = moment().add(-15,'days').format('YYYY-MM-DD');
	} else if (timeType == 'current_month') {
		beginDate = moment().add(-1,'months').format('YYYY-MM-DD');
	} else if (timeType == 'recent_three_month') {
		beginDate = moment().add(-3,'months').format('YYYY-MM-DD');
	} else {
		
	}
	$('#orderDate').data('daterangepicker').setStartDate(beginDate);
	$('#orderDate').data('daterangepicker').setEndDate(endDate);
	queryOrderData();
}

function queryOrderData(orderStatus, type, orderStatusName) {
	console.log($("#orderDate").val());
	orderStatus = "02";
	//获取参数
//	if (orderStatus == "" || orderStatus == null || orderStatus == undefined) {
//		orderStatus = $("#orderStatus").val();
//		orderStatusName = $("#orderStatusName").val();
//	}
	if (type == "" || type == null || type == undefined) {
		type = $("#type").val();
	}
	var timeType = $("#timeType").val();
	var searchDate = $("#orderDate").val();
	var startTime = null;
	var endTime = null;
	if (searchDate && searchDate.indexOf(' - ') > 0) {
		startTime = searchDate.split(' - ')[0];
		endTime = searchDate.split(' - ')[1];
	} 
//	var startTime = $("#startTime").val();
//	var endTime = $("#endTime").val();
	//组装参数
	var params = {
		orderStatus : orderStatus,
		timeType : timeType,
		startTime : startTime,
		endTime : endTime
	};
	//查询结果并组装图表
	$.ajax({
        type:"post",
        url:rootPath + "/order/queryOrderData",
        data:params,
        datatype: "json",
        success:function(json){
        	var myEcharts = echarts.init(document.getElementById("table"));
        	var allDate = json.allDateShow;
        	var dataSumValues = json.sumValues;
        	var dataMoneyValues = json.orderMoneyValues;
        	var tableName = type=='money' ? "订单金额" : "订单数量";
        	var formatter = type=='money' ? "￥{value}" : "{value}";
        	option = {
        		    tooltip: {
        		        trigger: 'axis'
        		    },
        			calculable : true,
        			legend : {
        				data : [ tableName ]
        			},
        		    xAxis:  {
        				axisLabel : {
        					show : true,
        					interval : 'auto'
        				// formatter: '{value}月',
        				},
        		        data: allDate
        		    },
        		    yAxis: {
        		    	type: 'value',
        		        name: tableName,
        		        axisLine : { // 轴线
        					show : true,
        					lineStyle : {
        						color : '#000000',
        						type : 'solid',
        						width : 1
        					}
        				},
        		        axisLabel: { //显示值
        		            formatter: formatter,
        					textStyle : {
        						color : '#000000',
        						fontFamily : 'verdana',
        						fontStyle : 'normal'
        					}
        		        },
        		        minInterval: 1
        		    },
        		    series: [
        		        {
        		            name:tableName,
        		            type:'line',
        		            data:type=='money' ? dataMoneyValues : dataSumValues,
            		        yAxisIndex: 0,
            		        itemStyle : {
            					normal : {
            						color : '#C23531',
            						borderWidth : 1
            					}
            				}
        		        }
        		    ]
        		};
        	myEcharts.setOption(option, true);
        },
        error: function(){
        	sys.showErr("审核失败");
        }
	});
	//保存查询用的参数作为下次的默认值
	$("#timeType").val(timeType);
	$("#type").val(type);
	$("#orderStatus").val(orderStatus);
	$("#orderStatusName").val(orderStatusName);
}